package com.beiding.jsonanalyzer.analyze.func.openfunc;

import com.beiding.jsonanalyzer.analyze.func.FuncBase;
import com.beiding.jsonanalyzer.analyze.func.FuncFactory;
import com.beiding.jsonanalyzer.analyze.func.base.FuncFactoryAdaptor;
import com.beiding.jsonanalyzer.analyze.query.ComparatorResult;
import com.beiding.jsonanalyzer.flow.ValueNode;

/**
 * 条件
 *
 * @author 丁常磊
 * @date 2022/5/16 13:05
 */

public class If {


    public static FuncFactory of(FuncFactory<FuncBase<ComparatorResult>> query, Object isTrue, Object isFalse) {

        FuncFactory fa = FuncUtils.ensureFuncFactory(isTrue);
        FuncFactory fb = FuncUtils.ensureFuncFactory(isFalse);

        return new FuncFactoryAdaptor() {
            @Override
            protected FuncBase newInstance() {
                FuncBase<ComparatorResult> baseQuery = query.createInstance();
                FuncBase ia = fa.createInstance();
                FuncBase ib = fb.createInstance();
                boolean agg = baseQuery.checkAgg() || ia.checkAgg() || ib.checkAgg();
                return new FuncBase() {
                    @Override
                    public boolean checkAgg() {
                        return agg;
                    }

                    @Override
                    public Object executeOne(ValueNode valueNode) {
                        if (baseQuery.executeOne(valueNode) == ComparatorResult.TRUE) {
                            return ia.executeOne(valueNode);
                        }
                        return ib.executeOne(valueNode);
                    }

                    @Override
                    public void pugAgg(ValueNode valueNode) {
                        ia.pugAgg(valueNode);
                        ib.pugAgg(valueNode);
                    }

                    @Override
                    public void resetAgg() {
                        ia.resetAgg();
                        ib.resetAgg();
                    }

                    @Override
                    public Object aggGet() {
                        if (baseQuery.aggGet() == ComparatorResult.TRUE) {
                            return ia.aggGet();
                        }
                        return ib.aggGet();
                    }

                    @Override
                    public String toString() {
                        return "if("+baseQuery+","+ia+","+ib+ ")";
                    }
                };
            }
        };
    }

    public static FuncFactory of(FuncFactory<FuncBase<ComparatorResult>> query, Object isTrue) {
        return of(query, isTrue, null);
    }


}
